package io.gitee.sections.sequence.core.dao;

import io.gitee.sections.sequence.core.SequenceDefinition;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

public class InMemoryDataAccessor implements DataAccessor {
    private Map<SequenceDefinition, AtomicLong> data = new HashMap<>();

    @Override
    public Optional<SequenceDefinition> find(String key) {
        return data.keySet().stream()
                .filter(definition -> definition.getKey().equals(key))
                .findFirst();
    }

    @Override
    public void insert(SequenceDefinition definition) {
        data.putIfAbsent(definition, new AtomicLong(definition.getInitial()));
    }

    @Override
    public void update(SequenceDefinition definition) {
        final AtomicLong atomicLong = data.get(definition);
        data.put(definition, atomicLong);
    }

    @Override
    public long grow(SequenceDefinition definition) {
        AtomicLong oldNumber = data.get(definition);
        long increase = definition.getCacheSize() * definition.getStepSize();
        return oldNumber.addAndGet(increase);
    }

    @Override
    public void close() {
        //doNothing
    }
}
